package com.hyts.xmlparser.base.handler.file;

import com.alibaba.fastjson.util.IOUtils;
import com.hyts.xmlparser.base.handler.AbstractXmlTransferHandler;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;

import java.io.*;
import java.nio.file.Path;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.xmlparser.handler.file
 * author:Libo/Alex
 * create-date:2019-07-18 10:48
 * email:liboware@gmail.com
 * @author Administrator
 */
public abstract class BaseXmlStreamTransferHandler<T> extends AbstractXmlTransferHandler<T> {


    @Override
    public T transfer(File param) {
        try (
           FileReader fr = new FileReader("D:\\ObjectStreamSample.xml");
           BufferedReader br = new BufferedReader(fr);
           ObjectInputStream input = getXStream().createObjectInputStream(br);
        ){
            return (T) input.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void transfer(T param, File param2) {
        ObjectOutputStream out = null;
        try (
            PrintWriter printWriter = new PrintWriter(param2)
        ){
            PrettyPrintWriter ppw = new PrettyPrintWriter(printWriter);
            // （4）创建对象输出流
            out = getXStream().createObjectOutputStream(ppw);
            out.writeObject(param);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(out);
        }
    }

    @Override
    public void transfer(T param, String filePath) {
        transfer(param,new File(filePath));
    }

    @Override
    public void transfer(T param, Path path) {
        transfer(param,path.toFile());
    }
}
